﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
using System.Text;
using ankietyzacja.Logic;
using ankietyzacja.Dao;
using System.Data;
using System.IO;
using ankietyzacja.Properties;


namespace ankietyzacja
{
    public partial class Email : System.Web.UI.Page
    {
        public Int32 EmailId;

        private void setControlsVisible(Boolean visible)
        {


            LinkButton EditLinkButton = (LinkButton)EmailDetailsView.FindControl("EditLinkButton");

            DodajAdresatowButton.Visible = visible;
            if (EditLinkButton != null)
            {
                EditLinkButton.Visible = visible;
            }
            AdresaciGridView.Columns[4].Visible = visible;
            AnkietyGridView.Columns[2].Visible = visible;
            DostepneAnkietyDropDownList.Visible = visible;
            DodajAnkieteButton.Visible = visible;
            DostepneAnkietyLabel.Visible = visible;
            SendButton.Visible = visible;
            UtworzKopieButton.Visible = !visible;

        }


        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                EmailId = Int32.Parse(Request.QueryString["email_id"]);
            }
            catch (ArgumentNullException ex)
            {
                throw (new AccessViolationException("Brak identyfikatora e-maila."));
            }

            EmailSqlDataSource.SelectParameters["EMAIL_ID"].DefaultValue = EmailId.ToString();
            EmailSqlDataSource.UpdateParameters["EMAIL_ID"].DefaultValue = EmailId.ToString();

            AdresaciSqlDataSource.SelectParameters["EMAIL_ID"].DefaultValue = EmailId.ToString();
            AdresaciSqlDataSource.DeleteParameters["EMAIL_ID"].DefaultValue = EmailId.ToString();

            AnkietySqlDataSource.SelectParameters["EMAIL_ID"].DefaultValue = EmailId.ToString();

            DostepneAnkietySqlDataSource.SelectParameters["EMAIL_ID"].DefaultValue = EmailId.ToString();

            HiddenField DataWyslaniaHiddenField = (HiddenField)EmailDetailsView.FindControl("DataWyslaniaHiddenField");

            if (DataWyslaniaHiddenField.Value == "")
            {
                setControlsVisible(true); 
            }
            else
            {
                setControlsVisible(false);
            }




        }

        protected void DodajAdresatowButton_Click(object sender, EventArgs e)
        {
            Server.Transfer("Users.aspx?email_id=" + EmailId, true);
        }

        protected void DodajAnkieteButton_Click(object sender, EventArgs e)
        {
            if (DostepneAnkietyDropDownList.SelectedValue == "") {
                return;
            }
            
            String connectionString = ConfigurationManager.ConnectionStrings["ankietyzacjaConnectionString"].ConnectionString;

            SqlConnection connection = new SqlConnection(connectionString);

            connection.Open();


            WyslanaAnkietaDao wyslanaAnkietaDao = new WyslanaAnkietaDao(connection, null);

            wyslanaAnkietaDao.insert(EmailId, Int32.Parse(DostepneAnkietyDropDownList.SelectedValue));

            DostepneAnkietyDropDownList.DataBind();

            AnkietyGridView.DataBind();


        }

        protected void AnkietyGridView_RowDeleted(object sender, GridViewDeletedEventArgs e)
        {
            DostepneAnkietyDropDownList.DataBind();
        }

        protected void UtworzKopieButton_Click(object sender, EventArgs e)
        {

            String connectionString = ConfigurationManager.ConnectionStrings["ankietyzacjaConnectionString"].ConnectionString;

            SqlConnection connection = new SqlConnection(connectionString);

            SqlTransaction transaction;

            connection.Open();
            transaction = connection.BeginTransaction();


            EmailDao emailDao = new EmailDao(connection, transaction);

            Int32 EmailIdNew = emailDao.kopiujEmail(EmailId);

            emailDao.kopiujUzytkownikEmail(EmailId, EmailIdNew);

            transaction.Commit();
            connection.Close();

            Server.Transfer("Email.aspx?email_id=" + EmailIdNew, false);

        }

        protected void SendButton_Click(object sender, EventArgs e)
        {


            AnkietyzacjaSmtpClient smtpClient = new AnkietyzacjaSmtpClient();



            String connectionString = ConfigurationManager.ConnectionStrings["ankietyzacjaConnectionString"].ConnectionString;

            SqlConnection connection = new SqlConnection(connectionString);

            SqlTransaction transaction;

            connection.Open();
            transaction = connection.BeginTransaction();


            EmailDao emailDao = new EmailDao(connection, transaction);
            WyslanaAnkietaDao wyslanaAnkietaDao = new WyslanaAnkietaDao(connection, transaction);



            DataTable emailDataTable = emailDao.load(EmailId);


            String emailSubject = emailDataTable.Rows[0]["TEMAT"].ToString();
            String emailContent = emailDataTable.Rows[0]["TRESC"].ToString();

            StreamReader streamReader = new StreamReader(Server.MapPath("~/Resources/EmailAnkietaLink.txt"));

            String linkTemplate = streamReader.ReadToEnd();

            DataTable wyslaneAnkietyDataTable = wyslanaAnkietaDao.loadForEmail(EmailId);


            foreach (DataRow row in wyslaneAnkietyDataTable.Rows)
            {


                String address = ankietyzacja.Properties.Settings.Default.ApplicationAddress + "/Survey.aspx?ankieta_id=" + row["ANKIETA_ID"];

                String link = linkTemplate.Replace("[adres]", address);
                link = link.Replace("[link]", row["NAZWAANKIETY"].ToString());

                emailContent += link;

                wyslanaAnkietaDao.updateDataWyslania(Int32.Parse(row["WYSLANAANKIETA_ID"].ToString()));


            }

            DataTable adresaciDataTable = emailDao.loadAdresaci(EmailId);


            foreach (DataRow adresaciRow in adresaciDataTable.Rows)
            {
                foreach (DataRow wyslanaAnkietaRow in wyslaneAnkietyDataTable.Rows)
                {
                    wyslanaAnkietaDao.insertUzytkownik(Int32.Parse(wyslanaAnkietaRow["WYSLANAANKIETA_ID"].ToString()), adresaciRow["UZYTKOWNIK_ID"].ToString());

                }
            }

            emailDao.updateDataWyslania(EmailId);

            transaction.Commit();
            connection.Close();

            foreach (DataRow adresaciRow in adresaciDataTable.Rows)
            {
                smtpClient.sendEmail(emailSubject, emailContent, adresaciRow["Email"].ToString(), true);

            }            
            
            setControlsVisible(false);

            KomunikatLabel.Text = "E-mail został wysłany.";

        }






    }
}